/**     
 * @Title: Producer.java   
 * @Package me.mq.producer   
 * @Description: TODO
 * @author weiwei 
 * @date 2018年5月30日 上午11:50:08   
 * @version V1.0     
 */
package me.mq.producer;

import me.mq.RabbitMQConfig;
import me.mq.RedisConfig;
import me.mq.entity.RabbitMetaMessage;
import me.mq.util.DefaultKeyGenerator;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.lang.Console;

/**
 * @ClassName: Producer
 * @Description: TODO
 * @author weiwei
 * @date 2018年5月30日 上午11:50:08
 * 
 */
@RestController
public class Producer {

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@SuppressWarnings("rawtypes")
	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private DefaultKeyGenerator keyGenerator;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GetMapping("/sendMessage")
	public Object sendMessage() {
		new Thread(() -> {
			HashOperations hashOperations = redisTemplate.opsForHash();
			for (int i = 0; i < 3; i++) {
				String id = keyGenerator.generateKey() + "";
				String value = "message " + i;
				RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage(value);
				// 先把消息存储到 redis
				hashOperations.put(RedisConfig.RETRY_KEY, id, rabbitMetaMessage);
				Console.log("send message = {}", value);
				// 再发送到 rabbitmq
				rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME, RabbitMQConfig.ROUTING_KEY, value, (message) -> {
					message.getMessageProperties().setMessageId(id);
					return message;
				}, new CorrelationData(id));
			}
		}).start();
		return "ok";
	}

}